package com.yfl.logistics.shiro;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yfl.logistics.pojo.Role;
import com.yfl.logistics.pojo.User;
import com.yfl.logistics.service.impl.PermissionServiceImpl;
import com.yfl.logistics.service.impl.RoleServiceImpl;
import com.yfl.logistics.service.impl.UserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private RoleServiceImpl roleService;
    @Autowired
    private PermissionServiceImpl permissionService;
    //获取授权信息的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取认证的信息
        User user = (User) principalCollection.getPrimaryPrincipal();

        //查询当前权限拥有的权限表达式
        List<String> expressions = permissionService.selectRolePermissionIds(user.getRoleId());

        //创建授权信息对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //将授权对象的权限表达式和角色信息添加到授权信息对象中
        simpleAuthorizationInfo.addRole(user.getRolename());
        simpleAuthorizationInfo.addStringPermissions(expressions);

        return simpleAuthorizationInfo;
    }

    //获取认证信息方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
     //获取token里的身份信息
        System.out.println("认证方法===================");
        String username = (String)authenticationToken.getPrincipal();

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userService.getOne(wrapper);
        //获取密码
        if (user == null){
            return  null;
        }

        //设置角色
        QueryWrapper<Role> roleWrqpper=new QueryWrapper<>();
        roleWrqpper.eq("role_id",user.getRoleId());
        Role role = roleService.getOne(roleWrqpper);

        user.setRolename(role.getRolename());

        //获取密码
        String password = user.getPassword();
        //获取盐
        String salt = user.getSalt();

        //创建信息认证对象
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, password, ByteSource.Util.bytes(salt),this.getName());

        return simpleAuthenticationInfo;
    }
}
